

    <script src="../base64.js"></script>
    <script src="../crypto-js.js"></script>
    <script src="../../dist/index.umd.js"></script>
    <script src="./index.js"></script>
<div class="page">
  <div class="title" id="title">血塞通软胶囊说明书</div>
  <div class="title1">请仔细阅读说明书并在医师指导下使用</div>
  <div class="btn">活血化瘀 通脉活络</div>
  <div id="FWBcontent"></div>
  <audio id="audioPlayer" controls style="display:none"></audio>

</div>

<textarea
id="textarea"
style="display: none;"
placeholder="请输入您要合成的文本"
>
</textarea>
<div style="display: none;">
  <div>语速([0-100])：<input id="speed" value="50" /></div>
  <div>音量([0-100])：<input id="volume" value="50" /></div>
  <div>音高([0-100])：<input id="pitch" value="50" /></div>
  <div>发音人：<input id="vcn" value="xiaoyan" /></div>
  <!-- x4_lingxiaolu_en -->
  <div>小语种(泰语)：<input id="tte" type="checkbox" /></div>
  <div>注意：发音人与语种会关联，小语种需要开通指定发音人</div>
</div>
<div style="display: none;">
  <button id="controll_tts">立即合成</button>
  <button id="download_pcm">下载pcm</button>
  <button id="download_wav">下载wav</button>
</div>
<div id="result" style="display: none;"></div>

<script>
  var hrefNum = window.location.href.split('=')[1]
  getContent(hrefNum)

  var speckConent="";
  function handleSpeak2(msgData){
    speckConent=msgData;
    connectWebSocket();
  };
  function handleSpeak1(msg) {
    fetch("https://tsn.baidu.com/text2audio?tok=" + "24.ee8ce38fc0723287ab1b28f1a29e8b3a.2592000.1736909688.282335-116670895" +
      "&tex=" + msg +
      "&cuid=MQtX1eobGiuaFK4rbomQRDs8jHcvnms1&ctp=1&lan=zh&spd=5&pit=5&vol=5" +
      "&per=0" +
      "&aue=3")
      .then(response => response.blob()) // 将响应转换为Blob
      .then(blob => {
        // 创建一个URL表示此blob对象
        const blobUrl = URL.createObjectURL(blob);
        // 设置audio元素的src属性为新创建的URL
        document.getElementById('audioPlayer').src = blobUrl;
        // 播放音频
        document.getElementById('audioPlayer').play();
      });
  }

  var voiceType="xiaoyu"
  function getContent(hrefNum) {
    fetch("http://121.41.46.17:8086/system/meidicineInfo/" + hrefNum)
      .then(response => response.json())
      .then(res => {
        var data = res.data
        console.log(data,'data');
        voiceType =  data.voiceType;
        document.getElementById('title').innerHTML = data.medicineCnName;
        var htmlContent = ""
        for (let i = 0; i < data.medicineDetails.length; i++) {
          htmlContent += `
        <div class="content" >
          <div class="content-flex">
          <div class="content-title">【${data.medicineDetails[i].title}】</div>
            <button onclick="handleSpeak2('${data.medicineDetails[i].content}')">
              <img class="content-img" src="https://rb.biomedical-wh.com/prod-api//profile/bdm_img/broadcast.png" alt="" />
            </button>
          </div>
          <div class="content-info">${data.medicineDetails[i].content}</div>
        </div>`
        }
        document.getElementById('FWBcontent').innerHTML = htmlContent;

      });
  }

  /////
  const APPID = "b932cdd0";
   const API_SECRET = "NWUwYjczM2RkOGI3Y2QxOTQ2NTRmNzJj";
   const API_KEY = "1382eb84a2cda4a28cfd116e6b728ee6";
  
  let btnControl = document.getElementById("controll_tts");
  let btnStatus = "UNDEFINED"; // "UNDEFINED" "CONNECTING" "PLAY" "STOP"
  function changeBtnStatus(status) {
    // btnStatus = status;
    // if (status === "UNDEFINED") {
    //   btnControl.innerText = "立即合成";
    // } else if (status === "CONNECTING") {
    //   btnControl.innerText = "正在合成";
    // } else if (status === "PLAY") {
    //   btnControl.innerText = "停止播放";
    // } else if (status === "STOP") {
    //   btnControl.innerText = "重新播放";
    // }
  }

  const audioPlayer = new AudioPlayer("../../dist");
  audioPlayer.onPlay = () => {
    changeBtnStatus("PLAY");
  };
  audioPlayer.onStop = (audioDatas) => {
    console.log(audioDatas);
    btnStatus === "PLAY" && changeBtnStatus("STOP");
  };
  function getWebSocketUrl(apiKey, apiSecret) {
    var url = "wss://tts-api.xfyun.cn/v2/tts";
    var host = location.host;
    var date = new Date().toGMTString();
    var algorithm = "hmac-sha256";
    var headers = "host date request-line";
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/tts HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    return url;
  }
  function encodeText(text, type) {
    if (type === "unicode") {
      let buf = new ArrayBuffer(text.length * 4);
      let bufView = new Uint16Array(buf);
      for (let i = 0, strlen = text.length; i < strlen; i++) {
        bufView[i] = text.charCodeAt(i);
      }
      let binary = "";
      let bytes = new Uint8Array(buf);
      let len = bytes.byteLength;
      for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary);
    } else {
      return Base64.encode(text);
    }
  }

  let ttsWS;
  function connectWebSocket() {
    const url = getWebSocketUrl(API_KEY, API_SECRET);
    if ("WebSocket" in window) {
      ttsWS = new WebSocket(url);
    } else if ("MozWebSocket" in window) {
      ttsWS = new MozWebSocket(url);
    } else {
      alert("浏览器不支持WebSocket");
      return;
    }
    changeBtnStatus("CONNECTING");
    
    ttsWS.onopen = (e) => {
      audioPlayer.start({
        autoPlay: true,
        sampleRate: 16000,
        resumePlayDuration: 1000
      });
      changeBtnStatus("PLAY");
     // var tte = document.getElementById("tte").checked ? "unicode" : "UTF8";
     var tte =  "UTF8";
      var params = {
        common: {
          app_id: APPID,
        },
        business: {
          aue: "raw",
          auf: "audio/L16;rate=16000",
          vcn: voiceType,
          speed: 50,
          volume: 50,
          pitch: 50,
          bgs: 1,
          tte,
        },
        data: {
          status: 2,
          text: encodeText(speckConent, tte),
        },
      };
      ttsWS.send(JSON.stringify(params));
    };
    ttsWS.onmessage = (e) => {
      let jsonData = JSON.parse(e.data);
      // 合成失败
      if (jsonData.code !== 0) {
        console.error(jsonData);
        changeBtnStatus("UNDEFINED");
        return;
      }
      audioPlayer.postMessage({
        type: "base64",
        data: jsonData.data.audio,
        isLastData: jsonData.data.status === 2,
      });
      if (jsonData.code === 0 && jsonData.data.status === 2) {
        ttsWS.close();
      }
    };
    ttsWS.onerror = (e) => {
      console.error(e);
    };
    ttsWS.onclose = (e) => {
      // console.log(e);
    };
  };



  // document.getElementById("textarea").onchange =
  //   document.getElementById("speed").onchange =
  //   document.getElementById("volume").onchange =
  //   document.getElementById("pitch").onchange =
  //   document.getElementById("vcn").onchange =
  //     () => {
  //       changeBtnStatus("UNDEFINED");
  //       ttsWS?.close();
  //       audioPlayer.reset();
  //     };
  // document.getElementById("tte").onchange = (e) => {
  //   let checked = e.target.checked;
  //   let text = `
  //           春江花月夜
  //   春江潮水连海平，海上明月共潮生。
  //   滟滟随波千万里，何处春江无月明。
  //   江流宛转绕芳甸，月照花林皆似霰。
  //   空里流霜不觉飞，汀上白沙看不见。
  //   江天一色无纤尘，皎皎空中孤月轮。
  //   江畔何人初见月？江月何年初照人？
  //   人生代代无穷已，江月年年望相似。
  //   不知江月待何人，但见长江送流水。
  //   白云一片去悠悠，青枫浦上不胜愁。
  //   谁家今夜扁舟子？何处相思明月楼？
  //   可怜楼上月徘徊，应照离人妆镜台。
  //   玉户帘中卷不去，捣衣砧上拂还来。
  //   此时相望不相闻，愿逐月华流照君。
  //   鸿雁长飞光不度，鱼龙潜跃水成文。
  //   昨夜闲潭梦落花，可怜春半不还家。
  //   江水流春去欲尽，江潭落月复西斜。
  //   斜月沉沉藏海雾，碣石潇湘无限路。
  //   不知乘月几人归，落月摇情满江树。`;
  //   document.getElementById("vcn").value = "xiaoyan";
  //   if (checked) {
  //     document.getElementById("vcn").value = "yingying";
  //     text =
  //       "สวัสดียินดีต้อนรับทุกท่านสู่การใช้ระบบการสังเคราะห์เสียงพูดในเที่ยวบินของมหาวิทยาลัยวิทยาศาสตร์และเทคโนโลยี";
  //   }
  //   document.getElementById("textarea").value = text;
  //   changeBtnStatus("UNDEFINED");
  //   ttsWS?.close();
  //   audioPlayer.reset();
  // };


  
  // document.getElementById("controll_tts").onclick = function () {
    
  //   if (btnStatus === "UNDEFINED") {
  //     // 开始合成
  //     connectWebSocket();
  //   } else if (btnStatus === "CONNECTING") {
  //     // 停止合成
  //     changeBtnStatus("UNDEFINED");
  //     ttsWS?.close();
  //     audioPlayer.reset();
  //     return;
  //   } else if (btnStatus === "PLAY") {
  //     audioPlayer.stop();
  //   } else if (btnStatus === "STOP") {
  //     audioPlayer.play();
  //   }
  // };
  // document.getElementById("download_pcm").onclick = function () {
  //   const blob = audioPlayer.getAudioDataBlob("pcm")
  //   if (!blob) {
  //     return
  //   }
  //   let defaultName = new Date().getTime();
  //   let node = document.createElement("a");
  //   node.href = window.URL.createObjectURL(blob);
  //   node.download = `${defaultName}.pcm`;
  //   node.click();
  //   node.remove();
  // };
  
  // document.getElementById("download_wav").onclick = function () {
  //   const blob = audioPlayer.getAudioDataBlob("wav")
  // if (!blob) {
  //   return
  // }
  //   let defaultName = new Date().getTime();
  //   let node = document.createElement("a");
  //   node.href = window.URL.createObjectURL(blob);
  //   node.download = `${defaultName}.wav`;
  //   node.click();
  //   node.remove();
  // };

</script>
<style>
  .page {
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 20px;
  }

  .title {
    width: 100%;
    text-align: center;
    font-size: 60px;
    font-weight: bold;
  }

  .title1 {
    font-size: 40px;
    width: 70%;
    text-align: center;
    font-weight: 600;
    margin-top: 20px;
  }

  .btn {
    width: 80%;
    height: 100px;
    background: #eef0f1;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    font-size: 45px;
    margin-top: 30px;
    font-weight: 400;

    align-items: center;
  }

  .content {
    width: 100%;
    padding: 0 30px;
    margin-top: 30px;
  }

  .content-img {
    width: 45px;
    height: 45px;
  }

  .content-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .content-title {
    font-weight: 500;
    font-size: 45px;
    margin: 10px 0;
  }

  .content-info {
    font-size: 26px;
    margin: 10px 0;
    color: #7e7d7d;
  }

  .button {
    background: none;
  }
</style>
